package com.wxy.service.Impl;

import cn.hutool.json.JSONUtil;
import com.wxy.dao.UserMapper;
import com.wxy.domain.User;
import com.wxy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 47868
 */
@Component("UserService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public List<User> findAll() {
        List<User> list = userMapper.selectList(null);
        return list;
    }

    @Override
    public User findById(int id) {
        //从redis中查询数据
        String redisUserString=stringRedisTemplate.opsForValue().get("user:"+id);
        //不为空，返回
        if(redisUserString!=null) {
        User redisUser = JSONUtil.toBean(redisUserString, User.class);
        System.out.println(redisUser.toString());
        return redisUser;}
        //为空，查询数据库
        User dbUser = userMapper.selectById(id);
        //查询数据库不为空，将数据存入reids，并返回
        if(dbUser!= null){
            stringRedisTemplate.opsForValue().set("user:"+dbUser.getId(), JSONUtil.toJsonStr(dbUser),2, TimeUnit.MINUTES);
            return dbUser;
        }
        else {
            return null;
        }
    }

    @Override
    public int updateById(int id, String password) {
        int n=userMapper.updatePasswordById(id,password);
        stringRedisTemplate.delete("user:"+id);
        return n;
    }
}
